class BubbleSort {
    constructor() {
        this.numbers = [];
        this.currentStep = 0;
        this.isRunning = false;
        this.currentIndex = 0;
        this.currentRound = 1;
        this.sortedIndex = this.numbers.length;
        this.isAutoSorting = false;
        
        this.initializeElements();
        this.bindEvents();
    }

    initializeElements() {
        this.container = document.getElementById('numbersContainer');
        this.currentStepDisplay = document.getElementById('currentStep');
        this.generateNewBtn = document.getElementById('generateNew');
        this.startSortBtn = document.getElementById('startSort');
        this.nextStepBtn = document.getElementById('nextStep');
        this.resetBtn = document.getElementById('reset');
    }

    bindEvents() {
        this.generateNewBtn.addEventListener('click', () => this.generateNumbers());
        this.startSortBtn.addEventListener('click', () => this.startSort());
        this.nextStepBtn.addEventListener('click', () => this.nextStep());
        this.resetBtn.addEventListener('click', () => this.reset());
    }

    generateNumbers() {
        this.numbers = [];
        for (let i = 0; i < 6; i++) {
            this.numbers.push(Math.floor(Math.random() * 99) + 1);
        }
        this.reset();
        this.renderNumbers();
    }

    renderNumbers() {
        this.container.innerHTML = '';
        this.numbers.forEach((num, index) => {
            const box = document.createElement('div');
            box.className = 'number-box';
            box.textContent = num;
            box.style.transition = 'all 0.3s ease';
            this.container.appendChild(box);
        });
    }

    async startSort() {
        if (this.isRunning) return;
        this.isRunning = true;
        this.isAutoSorting = true;
        this.startSortBtn.disabled = true;
        this.generateNewBtn.disabled = true;
        this.nextStepBtn.disabled = true;
        
        const boxes = document.querySelectorAll('.number-box');
        boxes.forEach(box => {
            box.classList.remove('sorted', 'comparing');
        });
        
        for (let i = 0; i < this.numbers.length - 1; i++) {
            this.currentStepDisplay.textContent = `进入第 ${this.currentRound} 轮循环`;
            for (let j = 0; j < this.numbers.length - 1 - i; j++) {
                this.currentIndex = j;
                await this.compareAndSwap();
                await new Promise(resolve => setTimeout(resolve, 1000));
            }
            const lastUnsortedIndex = this.numbers.length - this.currentRound;
            boxes[lastUnsortedIndex].classList.add('sorted');
            this.currentRound++;
        }
        
        boxes[0].classList.add('sorted');
        this.finishSort();
    }

    async compareAndSwap() {
        const boxes = document.querySelectorAll('.number-box');
        
        boxes.forEach(box => box.classList.remove('comparing'));
        
        boxes[this.currentIndex].classList.add('comparing');
        boxes[this.currentIndex + 1].classList.add('comparing');

        this.updateStepDisplay();

        if (this.numbers[this.currentIndex] > this.numbers[this.currentIndex + 1]) {
            await this.animateSwap(boxes[this.currentIndex], boxes[this.currentIndex + 1]);
            
            [this.numbers[this.currentIndex], this.numbers[this.currentIndex + 1]] = 
            [this.numbers[this.currentIndex + 1], this.numbers[this.currentIndex]];
        } else {
            await new Promise(resolve => setTimeout(resolve, 500));
        }
    }

    async animateSwap(element1, element2) {
        return new Promise(resolve => {
            const content1 = element1.textContent;
            const content2 = element2.textContent;
            
            element1.classList.add('swap-right');
            element2.classList.add('swap-left');

            const handleAnimationEnd = () => {
                element1.classList.remove('swap-right');
                element2.classList.remove('swap-left');
                
                element1.textContent = content2;
                element2.textContent = content1;
                
                element1.removeEventListener('animationend', handleAnimationEnd);
                resolve();
            };

            element1.addEventListener('animationend', handleAnimationEnd);
        });
    }

    updateStepDisplay() {
        const roundInfo = `第 ${this.currentRound} 轮循环：`;
        const compareInfo = `正在比较第 ${this.currentIndex + 1} 个数 ${this.numbers[this.currentIndex]} 和第 ${this.currentIndex + 2} 个数 ${this.numbers[this.currentIndex + 1]}`;
        this.currentStepDisplay.innerHTML = `${roundInfo}<br>${compareInfo}`;
    }

    finishSort() {
        this.isRunning = false;
        this.isAutoSorting = false;
        this.startSortBtn.disabled = false;
        this.generateNewBtn.disabled = false;
        this.nextStepBtn.disabled = false;
        this.currentStepDisplay.textContent = '排序完成！';
        
        const boxes = document.querySelectorAll('.number-box');
        boxes.forEach(box => box.classList.add('sorted'));
    }

    reset() {
        this.currentIndex = 0;
        this.currentRound = 1;
        this.sortedIndex = this.numbers.length;
        this.isRunning = false;
        this.isAutoSorting = false;
        this.startSortBtn.disabled = false;
        this.generateNewBtn.disabled = false;
        this.nextStepBtn.disabled = false;
        this.currentStepDisplay.textContent = '准备开始...';
        this.renderNumbers();
        
        const boxes = document.querySelectorAll('.number-box');
        boxes.forEach(box => {
            box.classList.remove('sorted', 'comparing');
        });
    }

    async nextStep() {
        if (this.isAutoSorting) return;
        
        if (!this.isRunning) {
            this.isRunning = true;
            this.startSortBtn.disabled = true;
            this.generateNewBtn.disabled = true;
            
            const boxes = document.querySelectorAll('.number-box');
            boxes.forEach(box => {
                box.classList.remove('sorted', 'comparing');
            });
        }

        if (this.currentIndex >= this.numbers.length - this.currentRound) {
            const lastUnsortedIndex = this.numbers.length - this.currentRound;
            const boxes = document.querySelectorAll('.number-box');
            boxes[lastUnsortedIndex].classList.add('sorted');
            
            this.currentRound++;
            this.currentIndex = 0;
            
            if (this.currentRound >= this.numbers.length) {
                boxes[0].classList.add('sorted');
                this.finishSort();
                return;
            }
        }

        await this.compareAndSwap();
        this.currentIndex++;
    }
}

// 初始化游戏
window.addEventListener('DOMContentLoaded', () => {
    const game = new BubbleSort();
    game.generateNumbers();
}); 